package com.pickup.rabbitMQ.consumer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.GetResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Objects;
import java.util.concurrent.TimeoutException;


@Slf4j
@Component
public class RabbitMqConsumer {

    static Connection connection;
    static Channel channel;
    static {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.10");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("/");
        try {
            connection = factory.newConnection();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }

        try {
            channel = connection.createChannel();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public HashSet<String> consumerConfig(String queueName, String userId) throws Exception {
        //第二个参数是否持久化
        channel.queueDeclare(queueName, true, false, false, null);
        HashSet<String> setSign = new HashSet<>();

        while (true) {
            GetResponse getResponse = channel.basicGet(queueName, true);
            if (getResponse == null) {
                break;
            }
            String s = new String(getResponse.getBody(), StandardCharsets.UTF_8);
            String[] str = s.split(",");
            if (Objects.equals(str[0], userId)) {
                setSign.add(str[1]);
            }
        }
        return setSign;
    }
}

